<template>
    <div class="portal-detail-container form-list-wrap" v-loading="loading">
        <app-cate v-model="form.app_id" v-if="appCateShow"></app-cate>
        <div class="table-wrapper">
            <div class="query-search-thin" style="margin-bottom: 10px;">
                <el-form :inline="true" size="mini" onsubmit="return false;">
                    <el-form-item>
                        <el-radio-group v-model="form.type" @change="refresh" style="float:left;">
                            <el-radio-button v-for="t in TYPES"
                                             :key="t.value"
                                             :label="t.value">{{t.name}}</el-radio-button>
                        </el-radio-group>
                        <!--<el-select v-model="form.type" @change="refresh">
                            <el-option
                                    v-for="t in TYPES"
                                    :key="t.value"
                                    :label="t.name"
                                    :value="t.value">
                            </el-option>
                        </el-select>-->
                    </el-form-item>
                    <el-form-item style="width:200px;margin-right:0px;">
                        <el-input placeholder="搜索页面名称" v-model="form.page_name"
                                  class="input-with-select" clearable
                                  @clear="refresh" @keyup.enter.native="refresh">
                            <el-button slot="append" icon="el-icon-search" @click="refresh()"></el-button>
                        </el-input>
                    </el-form-item>
                </el-form>
                <div class="btns">
                    <el-button type="primary" @click="showH5CreateWin()" size="mini" icon="el-icon-plus">H5页</el-button>
                    <el-button type="primary" @click="showCreateWin()" size="mini" icon="el-icon-plus">PC页</el-button>
                    <el-button type="primary" @click="showCustomCreateWin()" size="mini" icon="el-icon-plus">定制页</el-button>
                    <el-button type="primary" @click="showLinkCreateWin()" size="mini" icon="el-icon-plus">外链</el-button>
                </div>
            </div>
            <div class="m-table-container" ref="tableContainer">
                <el-table :data="pages" class="m-table" border size="mini" style="width: 100%" :height="tableHeight">
                    <el-table-column prop="page_name" label="页面名">
                        <template slot-scope="scope">
                            {{ scope.row.page_name }}
                            <i v-if="form.type === -1" class="icon-type-tag"
                               v-tippy="{ arrow: true }"
                               :content="scope.row.type | typeLabelName ">{{ scope.row.type | typeLabel }}</i>
                        </template>
                    </el-table-column>
                    <!--<el-table-column
                        label="创建人">
                        <template slot-scope="scope">
                            {{ scope.row.admin ? scope.row.admin.nickname : '' }}
                        </template>
                    </el-table-column>-->
                    <el-table-column prop="page_code" label="页面编码" width="260"></el-table-column>
                    <el-table-column prop="app.group_name" label="所属应用" width="100">
                        <template slot-scope="scope">
                            <div class="i-btn"
                                 v-tippy="{ arrow: true }"
                                 :content="(scope.row.app && scope.row.app.group_name) || '未分组'"
                                 @click="handleShowModuleSelectWin(scope.row, scope.$index)">
                                <i class="el-icon-edit"
                                   v-if="!scope.row.app || !scope.row.app.group_name"></i>
                                {{(scope.row.app && scope.row.app.group_name) || '未分组'}}
                            </div>
                        </template>
                    </el-table-column>

                    <el-table-column label="操作" width="320" align="center">
                        <template slot-scope="scope">
                            <el-button v-if="scope.row.type != 3"
                                size="mini"
                                type="text"
                                @click="handleView(scope.row, scope.$index)">预览</el-button>
                            <el-button v-if="scope.row.type == 3 || scope.row.type == 4"
                                    size="mini"
                                    type="text"
                                    @click="handleShowEditWin(scope.row, scope.$index)">修改</el-button>
                            <el-button v-if="scope.row.type != 3 && scope.row.type != 4"
                                size="mini"
                                type="text"
                                @click="handleEdit(scope.row, scope.$index)">设计</el-button>
                            <el-button v-if="scope.row.type != 4"
                                    size="mini"
                                    type="text"
                                    @click="handleShowSetting(scope.row, scope.$index, '1')">按钮管理</el-button>
                            <el-button v-if="scope.row.type != 3 && scope.row.type != 4"
                                    size="mini"
                                    type="text"
                                    @click="handleShowSetting(scope.row, scope.$index, '3')">低码开发</el-button>
                            <el-button v-if="scope.row.type != 4"
                                    size="mini"
                                    type="text"
                                    @click="handleShowViews(scope.row, scope.$index)">视图管理</el-button>
                            <el-button
                                size="mini"
                                type="text"
                                @click="handleDelete(scope.row, scope.$index)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <el-pagination
                    @size-change="refresh"
                    @current-change="refresh"
                    :current-page.sync="pagination.page"
                    :page-sizes="[10, 20, 50, 100]"
                    :page-size.sync="pagination.pageSize"
                    layout="total, sizes, prev, pager, next"
                    :total="pagination.total">
            </el-pagination>
        </div>

        <!--<el-dialog v-if="currentPage" :title="'预览页面：' + currentPage.page_name"
                   :visible.sync="pagePreviewShow" custom-class="m-dialog-fullscreen"
                   :close-on-click-modal="false" :append-to-body="true" :fullscreen="true">
            <jzl-page-web v-if="currentPage.type == 1" :page-id="currentPage.page_id"></jzl-page-web>
            <jzl-page-h5 v-else-if="currentPage.type == 2" :page-id="currentPage.page_id" style="width:375px;margin: 10px auto;"></jzl-page-h5>
        </el-dialog>-->

        <!--<el-dialog title="查看" :visible.sync="showView" top="60px" :append-to-body="true">
            <c-view @close="closeWin" :rid.sync="rid" :show.sync="showView"></c-view>
        </el-dialog>-->

        <!--<el-dialog title="增加" :visible.sync="showCreate" custom-class="m-dialog-fullscreen-nh"
                   :close-on-click-modal="false" :append-to-body="true" :fullscreen="true">
            <jzl-page-builder-web v-if="showCreate" :in-page-id="currentPage && currentPage.page_id" :app-id="form.app_id"
                                  @close="handlePageBuilderClose()"></jzl-page-builder-web>
        </el-dialog>
        <el-dialog title="增加" :visible.sync="showH5Create" custom-class="m-dialog-fullscreen-nh"
                   :close-on-click-modal="false" :append-to-body="true" :fullscreen="true">
            <jzl-page-builder-h5 v-if="showH5Create" :in-page-id="currentPage && currentPage.page_id" :app-id="form.app_id"
                              @close="handleH5PageBuilderClose()"></jzl-page-builder-h5>
        </el-dialog>-->

        <el-dialog
          title="视图管理"
          v-model="viewShow"
          :fullscreen="true"
          custom-class="m-dialog-fullscreen"
          :close-on-click-modal="false"
          :append-to-body="true">
            <page-views v-if="viewShow"
                   :show.sync="viewShow"
                   :page-id="currentPage && currentPage.page_id"
                   :is-view="isView"
                   @close="viewShow = false"></page-views>
        </el-dialog>

        <!--<el-dialog title="按钮管理" :visible.sync="actionShow"
                   :fullscreen="true" custom-class="m-dialog-fullscreen"
                   :close-on-click-modal="false" :append-to-body="true">
            <actions v-if="actionShow"
                     :show.sync="actionShow"
                     :page-id="currentPage && currentPage.page_id"
                     :is-view="isView"
                     @close="actionShow = false"></actions>
        </el-dialog>

        <el-dialog title="低码开发" :visible.sync="lowcodeShow"
                   :fullscreen="true" custom-class="m-dialog-fullscreen"
                   :close-on-click-modal="false" :append-to-body="true">
            <lowcode v-if="lowcodeShow" style="border-top: 1px solid #409eff;"
                     :show="lowcodeShow"
                     :page="currentPage" :is-view="isView" @change="handleLowcodeChange"></lowcode>
        </el-dialog>-->

        <el-dialog
          :title="settingWinName"
          v-model="showSettingCreate"
          :fullscreen="true"
          custom-class="m-dialog-fullscreen"
          :close-on-click-modal="false"
          :append-to-body="true">
            <page-setting @close="handleCloseSettingWin" v-if="showSettingCreate"
                      :show.sync="showSettingCreate"
                      :step-active="settingStepActive"
                      :page-id="currentPage && currentPage.page_id"
                      :is-view="isView"></page-setting>
        </el-dialog>

	    <el-dialog
        title="定制页面注册"
        v-model="createShow"
        :close-on-click-modal="false"
        :append-to-body="true">
            <el-form
              :model="form"
              ref="createForm"
              :rules="rules"
              class="form mp-form"
              label-width="100px"
              size="small">
                <el-form-item label="页面编码" prop="page_code">
                    <el-input v-model="createForm.page_code" autocomplete="off" :disabled="isView || isEdit"></el-input>
                </el-form-item>
                <el-form-item label="页面名称" prop="page_name">
                    <el-input v-model="createForm.page_name" autocomplete="off" :disabled="isView"></el-input>
                </el-form-item>
                <el-form-item label="页面路由名" prop="view">
                    <el-input v-model="createForm.view" autocomplete="off" :disabled="isView"></el-input>
                </el-form-item>
                <el-form-item label="页面路由路径" prop="url">
                    <el-input v-model="createForm.url" autocomplete="off" :disabled="isView"></el-input>
                </el-form-item>

                <el-form-item label="页面介绍" prop="page_desc">
                    <el-input v-model="createForm.page_desc" type="textarea" :rows="2" autocomplete="off" :disabled="isView"></el-input>
                </el-form-item>

                <el-form-item v-if="isView">
                    <el-button type="primary" @click="handleCustomCloseWin()" size="default">确 定</el-button>
                </el-form-item>
                <el-form-item v-else>
                    <el-button type="primary" @click="handleSave()" size="default">确 定</el-button>
                    <el-button @click="handleCustomCloseWin()" size="default">取 消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
        <el-dialog
          title="外链"
          v-model="createLinkShow"
          :close-on-click-modal="false"
          :append-to-body="true">
            <el-form :model="form" ref="createForm" :rules="rules" class="form mp-form"
                     label-width="100px" size="small">
                <el-form-item label="页面编码" prop="page_code">
                    <el-input v-model="createLinkForm.page_code" autocomplete="off" :disabled="isView || isEdit"></el-input>
                </el-form-item>
                <el-form-item label="页面名称" prop="page_name">
                    <el-input v-model="createLinkForm.page_name" autocomplete="off" :disabled="isView"></el-input>
                </el-form-item>
                <!--<el-form-item label="页面路由名" prop="view">
                    <el-input v-model="createLinkForm.view" autocomplete="off" :disabled="isView"></el-input>
                </el-form-item>-->
                <el-form-item label="页面路由路径" prop="url">
                    <el-input v-model="createLinkForm.url" autocomplete="off" :disabled="isView"></el-input>
                </el-form-item>

                <el-form-item label="页面介绍" prop="page_desc">
                    <el-input v-model="createLinkForm.page_desc" type="textarea" :rows="2" autocomplete="off" :disabled="isView"></el-input>
                </el-form-item>

                <el-form-item v-if="isView">
                    <el-button type="primary" @click="handleLinkCloseWin()" size="default">确 定</el-button>
                </el-form-item>
                <el-form-item v-else>
                    <el-button type="primary" @click="handleLinkSave()" size="default">确 定</el-button>
                    <el-button @click="handleLinkCloseWin()" size="default">取 消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
    import { mapState, mapActions } from 'vuex';
    // import setting from './page-setting';
    // import views from './page-views';

    const DFT_FORM = {
        type: 3,
        page_code: '',
        page_name: '',
        page_desc: '',
        url: ''
    };
    const DFT_FORM_LINK = {
        type: 4,
        page_code: '',
        page_name: '',
        page_desc: '',
        url: ''
    };
    const TYPE_LABEL = {
        1: 'PC',
        2: 'H5',
        3: 'C',
        4: 'L'
    };
    const TYPE_LABEL_NAME = {
        1: 'PC页面',
        2: 'H5页面',
        3: '定制页',
        4: '链接'
    };

    export default {
        props: {
            mode: String,
            appId: Number,
            appCateShow: {
                type: Boolean,
                default: true
            }
        },
        data() {
            return {
                showCreate: false,
                modId: null,
                formLabelWidth: '160px',
                winName: '新增',

                showH5Create: false,

		        // modules: [],

                pages: [],
                loading: false,
                pagination: {
                    page: 1,
                    pageSize: 50,
                    total: 0
                },
                tableHeight: 500,

                TYPES: [{
                    name: '全部',
                    value: -1
                }, {
                    name: '大屏',
                    value: 1
                }, {
                    name: 'H5页',
                    value: 2
                }, {
                    name: '定制页',
                    value: 3
                }, {
                    name: '外链',
                    value: 4
                }, {
                    name: 'PC页面',
                    value: 5
                }],
                showView: false,

                form: {
                    page_name: '',
                    type: -1,
                    app_id: null
                },

                // pagePreviewShow: false,
                currentPage: {},

                actionShow: false,
                viewShow: false,
                lowcodeShow: false,
                isView: false,

                createForm: _.clone(DFT_FORM),
                createShow: false,

                createLinkShow: false,
                createLinkForm: _.clone(DFT_FORM_LINK),

                settingWinName: '高级设置',
                showSettingCreate: false,
                settingStepActive: '1'
            }
        },
        components: {
            // setting,
            // views
        },
        created () {
            // this.pid = this.$route.query.pid;
        },
        mounted () {
            // this.groupId = this.$route.params.groupId;
            this.init();
            this.refresh();
        },
        watch: {
            '$route' (to, from) {
                // this.groupId = this.$route.params.groupId;
                // this.refresh();
            },
            'form.app_id'() {
                this.refresh()
            },
            appId(val) {
                this.form.app_id = val;
            }
        },
        computed: {},
        filters: {
            typeLabel(type) {
                return TYPE_LABEL[ type ] || type;
            },
            typeLabelName(type) {
                return TYPE_LABEL_NAME[ type ] || type;
            }
        },
        methods: {
            async init() {
                // let modules = await this.getApps();
                // this.modules = modules;
                this.form.app_id = this.appId;

                this.$nextTick(() => {
                    this.handleResize();
                });
            },
            handleResize() {
                let rect = this.$refs.tableContainer.getBoundingClientRect();
                let height = _.get(rect, 'height');

                if(height > 0) {
                    this.tableHeight = height;
                }
                // console.log(rect);
            },
            _isGroup(data) {
                return !!_.get(data, 'group_id') && !_.get(data, 'content_id');
            },
            isApp(data) {
                return this._isGroup(data) && _.get(data, 'type') === 2;
            },
            /*async getApps() {
                let ret = await this.$japi.admin.getAdminMenuTree();
                let apps = _.get(ret, 'groups', []);
                let notgroupsApps = [];
                let def = {
                    group_name: '其他',
                    subs: []
                };

                _.each(apps, app => {
                    if(app && this.isApp(app)) {
                        notgroupsApps.push(app)
                    }
                });
                if(notgroupsApps && notgroupsApps.length) {
                    def.subs = notgroupsApps;
                    apps.push(def);
                }
                return apps;
            },*/
            async refresh() {
                let ret = await this.$japi.page.getPageList(this.form, this.pagination);
                this.pages = _.get(ret, 'rows', []);
                this.pagination.total = _.get(ret, 'count', 0);
            },
            closeWin(flag) {
                this.showCreate = false;
                this.showView = false;
                this.refresh();
            },
            showCreateWin() {
                this.showCreate = true;
                this.showView = false;
                this.modId = null;
                this.currentPage = null;
                this.winName = '新增页面';
            },
            handleView(page) {
                // this.pagePreviewShow = true;
                // this.currentPage = page;
                $WinPagePreview({
                    page: page,
                    pageId: _.get(page, 'page_id'),
                    pageCode: _.get(page, 'page_code')
                });
            },
            handleEdit(page) {
                this.currentPage = page;

                if(page.type === 1) {
                    this.showCreate = true;
                } else {
                    this.showH5Create = true;
                }
            },
            showH5CreateWin() {
                this.showH5Create = true;
                this.showView = false;
                this.modId = null;
                this.currentPage = null;
                this.winName = '新增页面';
            },
            showCustomCreateWin() {
                this.createShow = true;
                this.winName = '新增页面';
                this.currentPage = null;
                this.$refs.createForm && this.$refs.createForm.resetFields();
                this.createForm = _.defaults({
                    page_code: this.$utils.getNanoid(),
                    app_id: this.form.app_id
                }, DFT_FORM);
            },
            handleCustomCloseWin(flag) {
                this.createShow = false;
                this.refresh();
            },
            async handleShowCustomEditWin(page) {
                this.createShow = true;
                this.createForm = _.cloneDeep(page);
            },
            async handleSave() {
                let ret = await this.$japi.page.pageUpsert(this.createForm);

                if(ret) {
                    this.$message('创建成功！');
                    this.refresh()
                    this.createShow = false;
                }
            },
            showLinkCreateWin() {
                this.createLinkShow = true;
                this.winName = '新增页面';
                this.currentPage = null;
                this.$refs.createLinkForm && this.$refs.createLinkForm.resetFields();
                this.createLinkForm = _.defaults({
                    page_code: this.$utils.getNanoid(),
                    app_id: this.form.app_id
                }, DFT_FORM_LINK);
            },
            handleLinkCloseWin(flag) {
                this.createLinkShow = false;
                this.refresh();
            },
            async handleShowLinkEditWin(page) {
                this.createLinkShow = true;
                this.createLinkForm = _.cloneDeep(page);
            },
            async handleLinkSave() {
                let ret = await this.$japi.page.pageUpsert(this.createLinkForm);

                if(ret) {
                    this.$message('创建成功！');
                    this.refresh()
                    this.createLinkShow = false;
                }
            },
            handleShowEditWin(page) {
                if(!page || page.type < 0) {
                    return;
                }

                if(page.type === 3) {
                    this.handleShowCustomEditWin(page);
                } else if(page.type === 4) {
                    this.handleShowLinkEditWin(page);
                }
            },
            async _delete(id) {
                let ret = await this.$japi.page.removePage(id);

                if(ret) {
                    this.refresh()
                }
            },
            handleDelete(it) {

                if(!it || !it.page_id) {
                    return;
                }
                this.$confirm(`此操作将永久删除该页面【${it.page_name}】, 是否继续?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    await this._delete(it.page_id);
                }).catch(() => {
                    /*this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });*/
                });
            },
            handleShowCreate() {
                /*this.$router.push({
                    name: 'builder-web'
                });*/
            },
            handlePageBuilderClose() {
                this.showCreate = false;
                this.refresh();
            },
            handleH5PageBuilderClose() {
                this.showH5Create = false;
                this.refresh();
            },
            handleShowActions(page) {
                this.actionShow = true;
                this.currentPage = page;
            },
            handleShowViews(page) {
                this.viewShow = true;
                this.currentPage = page;
            },
            handleShowLowcode(page) {
                this.currentPage = page;
                this.lowcodeShow = true;
            },
            handleLowcodeChange() {},
	        handleShowModuleSelectWin(page) {
                $WinApps({
                    onSelect: async (app) => {
                        if(!app || !app.group_id) {
                            return;
                        }
                        let ret = await this.$japi.page.pageUpsert({
                            page_id: page.page_id,
                            app_id: app.group_id
                        });

                        if(ret) {
                            this.$message('变更成功！');
                            this.refresh();
                        }
                    },
                    onCancel() {}
                });
            },
            handleShowSetting(it, idx, stepActive) {
                this.currentPage = it;
                this.settingWinName = `【${it.page_name}】高级设置`;
                this.showSettingCreate = true;
                this.settingStepActive = stepActive;
            },
            handleCloseSettingWin() {
                this.showSettingCreate = false;
            },
        }
    }
</script>

<style lang="scss" scoped>
    .el-button [class*=el-icon-]+span {
        margin-left: 2px;
    }

    .el-tag {
        margin-right: 5px;

        &:last-child {
            margin-right: 0px;
        }
    }
    .i-btn {
        color:#409EFF;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
        cursor: pointer;
    }
    .i-tag {
        background: #90Aeff;
        color: #FFF;
        width: 20px;
        height: 20px;
        border-radius: 50%;
        line-height: 20px;
        margin: 0 auto;
        cursor: pointer;

        &:hover {
            background: #3a8ee6;
        }
    }
    .icon-type-tag {
        float: right;
        background: #90Aeff;
        color: #FFF;
        /*width: 12px;*/
        height: 12px;
        border-radius: 1px;
        line-height: 12px;
        margin-top: 5px;
        cursor: pointer;
        display: inline-block;
        text-align: center;
        transform: scale(.9);
        font-style: normal;
        padding: 1px 2px;
    }
</style>
